
package com.jf.cloud.order.controller.app;

import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.multishop.feign.ShopWalletFeignClient;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.cache.constant.OrderCacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.constant.OrderActivityType;
import com.jf.cloud.common.order.constant.OrderType;
import com.jf.cloud.common.order.constant.ReturnProcessStatusEnum;
import com.jf.cloud.common.order.dto.OrderRefundSearchDTO;
import com.jf.cloud.common.order.vo.EsOrderRefundVO;
import com.jf.cloud.common.order.vo.OrderItemVO;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.Arith;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.order.constant.*;
import com.jf.cloud.order.dto.app.OrderRefundDTO;
import com.jf.cloud.order.dto.app.OrderRefundDeliveryDTO;
import com.jf.cloud.order.model.*;
import com.jf.cloud.order.service.*;
import com.jf.cloud.order.vo.OrderRefundAddrVO;
import com.jf.cloud.order.vo.OrderRefundVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 订单退款记录信息
 *
 * @author zz
 * @date 2020-12-05 14:13:50
 */
@RestController("appOrderRefundController")
@RequestMapping("/order_refund")
@Tag(name = "app-订单退款记录信息")
public class OrderRefundController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderRefundController.class);

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderRefundAddrService orderRefundAddrService;

    @Autowired
    private ShopWalletFeignClient shopWalletFeignClient;

    @Autowired
    private OrderSettlementService orderSettlementService;

    @Autowired
    private RocketMQTemplate orderRefundTemplate;


    @GetMapping("/user_page")
    @Operation(summary = "用户退款订单搜索接口" , description = "用户退款订单搜索接口")
    public ServerResponseEntity<PageVO<OrderRefundVO>> pcPage(@Valid PageDTO pageDTO, @ParameterObject OrderRefundSearchDTO orderRefundSearchDTO) {
        PageVO<OrderRefundVO> orderRefundPage = orderRefundService.userOrderRefundPage(pageDTO, orderRefundSearchDTO);
        return ServerResponseEntity.success(orderRefundPage);
    }

    @PostMapping("/apply")
    @Operation(summary = "申请退款" , description = "申请退款")
    public ServerResponseEntity<Long> apply(@Valid @RequestBody OrderRefundDTO orderRefundParam) {
        Long userId = AuthUserContext.get().getUserId();
        // 获取订单信息
        Order order = orderService.getOrderByOrderIdAndUserId(orderRefundParam.getOrderId(), userId);

        // 商品是否已经发货
        boolean isDelivered = Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value()) || Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value());

        ServerResponseEntity<Long> checkOrderStatusResponse = checkOrderStatus(orderRefundParam, order, isDelivered);
        if (!checkOrderStatusResponse.isSuccess()) {
            LOGGER.error("申请退款失败，原因：{}", checkOrderStatusResponse.getMsg());
            return checkOrderStatusResponse;
        }

        // 生成退款单信息
        OrderRefund newOrderRefund = new OrderRefund();

        // 获取所有正在进行中的退款订单
        List<OrderRefund> orderRefunds = orderRefundService.getProcessOrderRefundByOrderId(order.getOrderId());

        for (OrderRefund orderRefund : orderRefunds) {
            if (Objects.equals(RefundType.ALL.value(), orderRefund.getRefundType())) {
                LOGGER.error("申请退款失败，原因：{}", "该订单正在进行整单退款，无法进行新的退款操作");
                return ServerResponseEntity.showFailMsg("该订单正在进行整单退款，无法进行新的退款操作");
            }
            if (Objects.equals(orderRefund.getOrderItemId(), orderRefundParam.getOrderItemId())) {
                LOGGER.error("申请退款失败，原因：{}", "该商品正在进行退款中，无法进行新的退款操作");
                return ServerResponseEntity.showFailMsg("该商品正在进行退款中，无法进行新的退款操作");
            }
        }

        // 如果存在分销订单，则计算分销总金额
        List<OrderItem> orderItemList = orderItemService.listOrderItemsByOrderId(order.getOrderId());
        // 获取所有的订单项总数
        int orderItemCount = orderItemList.size();
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        if (orderRefundParam.getRefundType().equals(RefundType.ALL.value())) {
            LOGGER.info("申请整单退款，订单号：{}", order.getOrderId());
            // 全部物品退款
            // 计算该订单项的分销金额
            newOrderRefund.setDistributionTotalAmount(orderService.sumTotalDistributionAmountByOrderItem(orderItemList));
            // 计算平台退款金额（退款时将这部分钱退回给平台，所以商家要扣除从平台这里获取的金额）
            newOrderRefund.setPlatformRefundAmount(order.getPlatformAmount());
            newOrderRefund.setPlatformRefundCommission(order.getPlatformCommission());
            newOrderRefund.setPurchaseRefundAmount(orderItemList.stream().mapToLong(OrderItem::getItemPurchaseAmount).sum());
            newOrderRefund.setPurPlatformRefundCommission(orderItemList.stream().mapToLong(OrderItem::getPurchasePlatformCommission).sum());
        } else {
            if (Objects.nonNull(orderRefundParam.getGiveawayItemIds())){
                RedisUtil.set(OrderCacheNames.REFUND_GIVEAWAY_ORDER_ITEM + orderRefundParam.getOrderItemId(), orderRefundParam.getGiveawayItemIds(), 3600);
            }
            LOGGER.info("申请单个物品退款，订单号：{}", order.getOrderId());
            ServerResponseEntity<Long> doItemRefundResponse = doItemRefund(orderRefundParam, order, isDelivered, newOrderRefund, orderRefunds, orderItemList, orderItemCount);
            if (!doItemRefundResponse.isSuccess()){
                LOGGER.error("申请退款失败，原因：{}", doItemRefundResponse.getMsg());
                return doItemRefundResponse;
            }
        }
        newOrderRefund.setSupplierId(0L);
        // 判断下是否为供应商订单,如果是商家代销供应商商品且为供应商发货设置供应商信息
        if (!Objects.equals(order.getSupplierId(),0L) && Objects.equals(order.getSupplierDeliveryType(),1)) {
            LOGGER.info("申请退款，订单号：{}，为供应商订单", order.getOrderId());
            newOrderRefund.setSupplierId(order.getSupplierId());
        }
        newOrderRefund.setShopId(order.getShopId());
        newOrderRefund.setUserId(order.getUserId());
        newOrderRefund.setOrderId(order.getOrderId());
        newOrderRefund.setRefundType(orderRefundParam.getRefundType());

        newOrderRefund.setRefundAmount(orderRefundParam.getRefundAmount());
        if (Objects.equals(RefundType.ALL.value(), orderRefundParam.getRefundType())) {
            newOrderRefund.setOrderItemId(0L);
            newOrderRefund.setRefundCount(order.getAllCount());
        } else {
            newOrderRefund.setOrderItemId(orderRefundParam.getOrderItemId());
            newOrderRefund.setRefundCount(orderRefundParam.getRefundCount());
        }
        newOrderRefund.setApplyType(orderRefundParam.getApplyType());
        if (Objects.equals(orderRefundParam.getApplyType(), RefundApplyType.REFUND_AND_RETURNS.value())) {
            LOGGER.info("申请退款，订单号：{}，申请类型：退货退款", order.getOrderId());
            newOrderRefund.setIsReceived(1);
        } else {
            newOrderRefund.setIsReceived(orderRefundParam.getReceived());
        }
        newOrderRefund.setBuyerReason(orderRefundParam.getBuyerReason());
        newOrderRefund.setBuyerDesc(orderRefundParam.getBuyerDesc());
        newOrderRefund.setBuyerMobile(orderRefundParam.getBuyerMobile());
        newOrderRefund.setImgUrls(orderRefundParam.getImgUrls());
        newOrderRefund.setReturnMoneySts(ReturnProcessStatusEnum.APPLY.value());
        newOrderRefund.setUpdateTime(new Date());
        orderRefundService.applyRefund(newOrderRefund);
        //TODO 如果是虚拟订单直接退款
        if(null !=order.getOrderMold() && order.getOrderMold() == 1){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                LOGGER.error("线程等待异常", e);
            }
            LOGGER.info("*********虚拟订单开始退款**********");
            com.jf.cloud.order.dto.multishop.OrderRefundDTO orderRefundParam1=new com.jf.cloud.order.dto.multishop.OrderRefundDTO();
            orderRefundParam1.setRefundId(newOrderRefund.getRefundId());
            orderRefundParam1.setSellerMsg("同意");
            orderRefundParam1.setRefundSts(2);
            orderRefundParam1.setSupplierHandleStatus(-1);
            orderRefundService.applyRefundByUnreal(orderRefundParam1);
            LOGGER.info("**********虚拟订单退款结束************");

        }
        return ServerResponseEntity.success(newOrderRefund.getRefundId());
    }


    private ServerResponseEntity<Long> doItemRefund(OrderRefundDTO orderRefundParam, Order order, boolean isDelivered, OrderRefund newOrderRefund, List<OrderRefund> orderRefunds, List<OrderItem> orderItemList, int orderItemCount) {
        // 部分物品退款
        OrderItemVO orderItemVO = orderItemService.getByOrderItemId(orderRefundParam.getOrderItemId());
        if (orderItemVO == null) {
            // 该物品在订单中不存在
            return ServerResponseEntity.fail(ResponseEnum.ORDER_NOT_EXIST);
        }

        boolean isCanRefund = true;
        //  查看是否有支付金额和积分都为空的订单，有则抛出异常
        for (OrderItem item : orderItemList) {
            if(!Objects.equals(item.getActivityType(), OrderActivityType.GIVEAWAY.value())) {
                if (item.getActualTotal() <= 0 && item.getUseScore() <= 0) {
                    isCanRefund = false;
                    break;
                }
            }
        }
        if (!isCanRefund) {
            // 该订单部分订单项支付金额和积分为0，无法使用部分退款
            return ServerResponseEntity.showFailMsg("该订单部分订单项支付金额和积分为0，无法使用部分退款");
        }

        if (Objects.equals(orderItemVO.getSpuMold(),1) && Objects.equals(orderRefundParam.getApplyType(),RefundApplyType.REFUND_AND_RETURNS.value())) {
            return ServerResponseEntity.showFailMsg("虚拟商品只能选择仅退款");
        }

//        // 是否为最后一项
//        boolean isEndItem = Objects.equals(orderRefunds.size(), orderItemCount - 1);
        // 用户实际能退的运费 = 订单当前运费 - 平台减免运费
        long freightAmount = order.getFreightAmount()  - order.getPlatformFreeFreightAmount();

        //赠品处理
        long itemActualTotal = orderItemVO.getActualTotal();
        long giveawayRefundAmount = 0;
        StringBuilder returnGiveawayIds = new StringBuilder();
        // 赠品处理
        giveawayRefundAmount = handleGiveawayProd(orderRefundParam, newOrderRefund, orderItemVO, giveawayRefundAmount, returnGiveawayIds);
        // 最多可以退的实付金额需要减去不退回的赠品退款金额,最小值应该为0.01，理论上赠品价值不可能大于商品
        itemActualTotal = (long) Arith.sub(itemActualTotal,giveawayRefundAmount);

        // 计算该订单项的分销金额
        OrderItem tempOrderItem = mapperFacade.map(orderItemVO, OrderItem.class);
        newOrderRefund.setDistributionTotalAmount(orderService.sumTotalDistributionAmountByOrderItem(Collections.singletonList(tempOrderItem)));

        // 计算平台退款金额（退款时将这部分钱退回给平台，所以商家要扣除从平台这里获取的金额）
        Long changePlatformAmount;
        // 平台佣金应退 = 平台佣金 *（退款金额 / 实付金额）
        Long changePlatformCommission;
        if (orderRefundParam.getRefundAmount() != itemActualTotal && orderRefundParam.getRefundAmount() != 0) {
            // 平台退款金额 = 平台优惠金额 *（退款金额 / 实付金额）
            changePlatformAmount = PriceUtil.divideByBankerRounding(orderItemVO.getPlatformShareReduce() * orderRefundParam.getRefundAmount(), itemActualTotal);
            changePlatformCommission = PriceUtil.divideByBankerRounding(orderItemVO.getPlatformCommission() * orderRefundParam.getRefundAmount(), itemActualTotal);
        } else {
            changePlatformAmount = orderItemVO.getPlatformShareReduce();
            changePlatformCommission = orderItemVO.getPlatformCommission();
        }
        // 此处设置实际平台抵现金额
        newOrderRefund.setPlatformRefundAmount(changePlatformAmount);

        newOrderRefund.setPlatformRefundCommission(changePlatformCommission);

        // 平台供应商佣金应退 = 平台供应商佣金 *（退款金额 / 实付金额）
        // 退款金额为0时，是纯积分退款，金额无法修改，直接从商品中取佣金
        Long changeSupplierPlatformCommission;
        if (orderRefundParam.getRefundAmount() == 0L) {
            changeSupplierPlatformCommission = orderItemVO.getPurchasePlatformCommission();
        } else {
            changeSupplierPlatformCommission = PriceUtil.divideByBankerRounding(orderItemVO.getPurchasePlatformCommission() * orderRefundParam.getRefundAmount(), itemActualTotal);
        }
        newOrderRefund.setPurPlatformRefundCommission(changeSupplierPlatformCommission);

        // 采购金额应退 = 采购金额 *（退款金额 / 实付金额）
        Long purchaseRefundAmount = PriceUtil.divideByBankerRounding(orderItemVO.getItemPurchaseAmount() * orderRefundParam.getRefundAmount(), itemActualTotal);
        newOrderRefund.setPurchaseRefundAmount(purchaseRefundAmount);

        newOrderRefund.setRefundActualTotal(itemActualTotal);

        // 退款物品数量为null或者0时，则为退款全部数量
        if (orderRefundParam.getRefundCount() <= 0) {
            orderRefundParam.setRefundCount(orderItemVO.getCount());
        }

        // 判断退款数量是否溢出
        if (orderRefundParam.getRefundCount() > orderItemVO.getCount()) {
            // 退款物品数量已超出订单中的数量，不允许申请
            return ServerResponseEntity.showFailMsg("退款物品数量已超出订单中的数量，不允许申请");
        }

        // 判断退款金额是否超出订单金额3种情况
        double refundSingleAmount = Arith.div(Arith.add(orderRefundParam.getRefundAmount(),giveawayRefundAmount), orderRefundParam.getRefundCount(), 3);
        refundSingleAmount = Arith.sub(refundSingleAmount,giveawayRefundAmount);

        // 单件退款金额
        double singleAmount = Arith.div(orderItemVO.getActualTotal(), orderItemVO.getCount(), 3);

        // 可以退款的实际金额应该为 当前退款数量 * singleAmount(单个最大退款金额) - 赠品金额,并且不能超过订单项的实付金额
        double productTotalAmount = orderItemVO.getSpuTotalAmount() + orderItemVO.getShopChangeFreeAmount() - giveawayRefundAmount;

//        // 1.如果是此笔订单最后一件并且不为确认收货或待收货状态，则订单项加上运费进行判断。(已不需要，现在前端退款金额不加上运费)
//        if (isEndItem && !isDelivered) {
//            productTotalAmount = Arith.add(productTotalAmount, freightAmount);
//            singleAmount = Arith.add(singleAmount, freightAmount);
//        }
        // 2.如果不是直接跟订单项进行判断
        if (refundSingleAmount > productTotalAmount || refundSingleAmount > singleAmount) {
            // 退款金额已超出订单金额，无法申请
            return ServerResponseEntity.showFailMsg("退款金额已超出订单金额，无法申请");
        }
        // 3.当前退款金额  +  已申请退款金额 > 订单实际支付总额， 就不能退款了
        double refundAmount = orderRefundParam.getRefundAmount();
        // 已退款总金额
        double alreadyRefundTotal = orderRefunds.stream().mapToDouble(OrderRefund::getRefundAmount).sum();
        if (Arith.add(refundAmount, alreadyRefundTotal) > order.getActualTotal()) {
            // 退款金额已超出订单金额，无法申请
            return ServerResponseEntity.showFailMsg("退款金额已超出订单金额，无法申请");
        }
        // 一个订单项只能申请一次退款
        for (OrderRefund orderRefund : orderRefunds) {
            if (Objects.equals(orderRefund.getOrderId(), orderItemVO.getOrderItemId())) {
                // 退款订单项已处理，请勿重复申请
                return ServerResponseEntity.showFailMsg("退款订单项已处理，请勿重复申请");
            }
        }
        return ServerResponseEntity.success();
    }

    private long handleGiveawayProd(OrderRefundDTO orderRefundParam, OrderRefund newOrderRefund, OrderItemVO orderItem, long giveawayRefundAmount, StringBuilder returnGiveawayIds) {
        // 判断是否为赠品的主商品--活动类型为赠品，且活动id等于0
        if(Objects.equals(orderItem.getMainGiveaway(), 1)) {
            boolean isReturnGiveaway = true;
            List<OrderItemVO> giveawayItemList = orderItemService.getOrderItemByGiveawayOrderItemId(orderItem.getUserId(), orderItem.getOrderItemId());
            List<Long> giveawayItemIds = orderRefundParam.getGiveawayItemIds();
            for (OrderItemVO giveawayItem : giveawayItemList) {
                if(giveawayItemIds.contains(giveawayItem.getOrderItemId())) {
                    returnGiveawayIds.append(giveawayItem.getOrderItemId()).append(StrUtil.COMMA);
                    continue;
                }
                isReturnGiveaway = false;
                // 不退回判断金额
                giveawayRefundAmount = (long) Arith.add(giveawayRefundAmount,giveawayItem.getGiveawayAmount());
            }
            // 如果是全部退回则不需要判断退款金额
            if(isReturnGiveaway){
                giveawayRefundAmount = 0;
            }
        }
        if(returnGiveawayIds.length() > 0){
            returnGiveawayIds.deleteCharAt(returnGiveawayIds.length() - 1);
            newOrderRefund.setReturnGiveawayIds(returnGiveawayIds.toString());
        }else{
            newOrderRefund.setReturnGiveawayIds(null);
        }
        return giveawayRefundAmount;
    }


    private ServerResponseEntity<Long> checkOrderStatus(OrderRefundDTO orderRefundParam, Order order, boolean isDelivered) {
        //待收货或者确认收货 -> 整单退款 -> 退款金额 < 订单金额 - 运费金额
        if (isDelivered && orderRefundParam.getRefundType().equals(RefundType.ALL.value())) {
            Long refundAmount = order.getActualTotal() - (order.getFreightAmount() - order.getPlatformFreeFreightAmount());
            if (Math.abs(orderRefundParam.getRefundAmount()) > refundAmount) {
                // 退款金额已超出订单金额，无法申请
                return ServerResponseEntity.showFailMsg("退款金额已超出订单金额");
            }
        }

        if (!Objects.equals(order.getIsPayed(), 1)) {
            // 当前订单还未付款，无法申请
            return ServerResponseEntity.showFailMsg("当前订单还未付款，无法申请退款");
        }

        if (Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())) {
            // 当前订单已失败，不允许退款
            return ServerResponseEntity.showFailMsg("当前订单已关闭");
        }

        if (Objects.equals(order.getStatus(), OrderStatus.WAIT_GROUP.value())) {
            // 当前订单正在等待成团状态，需等待成团才能进行下一步操作
            return ServerResponseEntity.showFailMsg("当前订单正在等待成团状态，需等待成团才能进行下一步操作");
        }

        if (Objects.equals(order.getStatus(), OrderStatus.WAIT_BALANCE.value())) {
            // 当前订单正在等待支付尾款状态，需完成支付尾款才能进行下一步操作
            return ServerResponseEntity.showFailMsg("当前订单正在等待支付尾款状态，需完成支付尾款才能进行下一步操作");
        }


        if (orderRefundParam.getRefundAmount() > order.getActualTotal()) {
            return ServerResponseEntity.showFailMsg("退款金额已超出订单金额，无法申请");
        }


        if (!orderRefundService.checkRefundDate(order)) {
            return ServerResponseEntity.showFailMsg("当前订单已超过可退款时间，无法退款");
        }
        if (Objects.equals(order.getOrderType(), OrderType.SCORE.value())) {
            //
            return ServerResponseEntity.showFailMsg("积分商品，无法退款");
        }

        boolean hasRefund =  !Objects.isNull(order.getRefundStatus()) && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value());
        if (Objects.equals(orderRefundParam.getRefundType(), RefundType.ALL.value()) && hasRefund) {
            // 该订单已有商品正在退款中，不能再进行整单退款
            return ServerResponseEntity.showFailMsg("该订单已有商品正在退款中，不能再进行整单退款");
        }
        return ServerResponseEntity.success();
    }

    /**
     * 用户提交物流公司信息
     */
    @PostMapping("/submit_express")
    @Operation(summary = "提交退款订单物流填写信息" , description = "提交退款订单物流填写信息")
    public ServerResponseEntity<Void> submitExpress(@Valid @RequestBody OrderRefundDeliveryDTO orderRefundExpressParam) {
        OrderRefundVO orderRefundVO = orderRefundService.getByRefundId(orderRefundExpressParam.getRefundId());
        if (Objects.isNull(orderRefundVO)) {
            // 查询不到退款信息
            return ServerResponseEntity.showFailMsg("退款订单不存在");
        }

        Long userId = AuthUserContext.get().getUserId();
        if (!Objects.equals(orderRefundVO.getUserId(), userId)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }

        if (!Objects.equals(orderRefundVO.getApplyType(), RefundApplyType.REFUND_AND_RETURNS.value())) {
            // 当前申请类型不允许提交物流信息操作
            return ServerResponseEntity.showFailMsg("当前申请类型不允许提交物流信息操作");
        }
        if (!Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.PROCESSING.value())
                && !Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.CONSIGNMENT.value())) {
            // 当前状态不允许提交物流信息操作
            return ServerResponseEntity.showFailMsg("当前状态不允许提交物流信息操作");
        }

        // 填写物流信息 申请退货的时候已经有退货信息了
        OrderRefundAddr orderRefundAddr = orderRefundAddrService.getByRefundId(orderRefundExpressParam.getRefundId());
        orderRefundAddr.setSenderMobile(orderRefundExpressParam.getMobile());
        orderRefundAddr.setSenderRemarks(orderRefundExpressParam.getSenderRemarks());
        orderRefundAddr.setDeliveryCompanyId(orderRefundExpressParam.getDeliveryCompanyId());
        orderRefundAddr.setDeliveryName(orderRefundExpressParam.getDeliveryName());
        orderRefundAddr.setDeliveryNo(orderRefundExpressParam.getDeliveryNo());
        orderRefundAddr.setImgs(orderRefundExpressParam.getImgs());
        orderRefundAddr.setCreateTime(new Date());

        OrderRefund orderRefund = mapperFacade.map(orderRefundVO, OrderRefund.class);
        orderRefundService.submitExpress(orderRefund, orderRefundAddr);
        // 提交成功
        return ServerResponseEntity.success();
    }


    /**
     * 用户撤销退货退款申请
     */
    @PutMapping("/cancel")
    @Operation(summary = "撤销退货退款申请")
    public ServerResponseEntity<Void> cancel(@RequestBody Long refundId) {
        OrderRefundVO orderRefundVO = orderRefundService.getByRefundId(refundId);
        if (Objects.isNull(orderRefundVO)) {
            // 撤销失败 退款订单不存在
            return ServerResponseEntity.showFailMsg("退款订单不存在");
        }
        if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.PROCESSING.value())) {
            // 卖家正在处理退款，不能撤销退款申请
            return ServerResponseEntity.showFailMsg("卖家正在处理退款，不能撤销退款申请");
        }
        if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.CONSIGNMENT.value())) {
            // 买家已发货，不能撤销退款申请
            return ServerResponseEntity.showFailMsg("买家已发货，不能撤销退款申请");
        }
        if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.RECEIVE.value())) {
            // 卖家已收货，不能撤销退款申请
            return ServerResponseEntity.showFailMsg("卖家已收货，不能撤销退款申请");
        }
        if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.SUCCESS.value())) {
            return ServerResponseEntity.showFailMsg("退款已成功，不能撤销退款申请");
        }
        Long userId = AuthUserContext.get().getUserId();

        // 查看订单是否还有处于处理中的退款单，如果没有则修改订单退款状态为关闭状态
        Order order = orderService.getOrderByOrderIdAndUserId(orderRefundVO.getOrderId(), userId);

        //如果订单状态为待发货、包含运费、单个商品退款，且所有订单项都进行退款，则不能再取消退款（取消退款后再退款会导致重复退运费bug）
        if (Objects.equals(order.getStatus(),OrderStatus.PAYED.value()) && Objects.equals(orderRefundVO.getRefundType(),RefundType.SINGLE.value())
                && order.getFreightAmount() - order.getPlatformFreeFreightAmount() > 0){
            // 退款数量
            int refundCount = orderRefundService.countByReturnMoneyStsAndOrderId(1, 6, order.getOrderId());
            // 订单项数量
            int orderItemCount = orderItemService.countByOrderId(order.getOrderId());
            if (refundCount == orderItemCount){
                // 该订单所有商品都进行退款，已无法取消退款
                return ServerResponseEntity.showFailMsg("该订单所有商品都进行退款，已无法取消退款");
            }
        }

        if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.SUCCESS.value()) ||
                Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.FAIL.value())) {
            // 撤销失败 当前状态不允许此操作
            return ServerResponseEntity.showFailMsg("撤销失败 当前状态不允许此操作");
        }

        orderRefundService.cancelRefund(orderRefundVO);



        return ServerResponseEntity.success();
    }

    /**
     * 查看退款订单详情
     */
    @GetMapping("/info")
    @Operation(summary = "查看退款订单详情" , description = "查看退款订单详情")
    public ServerResponseEntity<OrderRefundVO> info(@ParameterObject Long refundId) {
        // 查询详情
        OrderRefundVO orderRefundVO = orderRefundService.getDetailByRefundId(refundId);

        if (orderRefundVO == null) {
            // 查看失败 该退款订单不存在
            return ServerResponseEntity.showFailMsg("该退款订单不存在");
        }

        if (!Objects.equals(orderRefundVO.getUserId(), AuthUserContext.get().getUserId())) {
            // 查看失败 您没有此权限
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        // 退货地址
        if (Objects.equals(orderRefundVO.getApplyType(), RefundApplyType.REFUND_AND_RETURNS.value()) && orderRefundVO.getHandelTime() !=null) {
            OrderRefundAddr orderRefundAddr = orderRefundAddrService.getByRefundId(refundId);
            orderRefundVO.setOrderRefundAddr(mapperFacade.map(orderRefundAddr, OrderRefundAddrVO.class));
        }
        return ServerResponseEntity.success(orderRefundVO);
    }

    /**
     * 查看我的退款订单列表
     */
    @GetMapping("/page")
    @Operation(summary = "我的退款订单列表" , description = "我的退款订单列表，显示数量时候")
    public ServerResponseEntity<EsPageVO<EsOrderRefundVO>> list(PageDTO page, @ParameterObject OrderRefundSearchDTO orderRefundPageDTO) {
        orderRefundPageDTO.setUserId(AuthUserContext.get().getUserId());
        EsPageVO<EsOrderRefundVO> pageList = orderRefundService.page(page, orderRefundPageDTO);
//        PageVO<OrderRefundVO> pageList = orderRefundService.page(page, orderRefundPageDTO,SysTypeEnum.MULTISHOP.value());
        return ServerResponseEntity.success(pageList);
    }
}
